<div class="layui-tab layui-tab-card" lay-filter="tabForwardList">
  
  <ul class="layui-tab-title">
    <li class="layui-this">端口转发列表</li>
    <li>快捷功能</li>
    <li>帮助说明</li>
  </ul>
  <div class="layui-tab-content" style="height: auto;">

    
    <div class="layui-tab-item layui-show">
      
      <div class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="app-content-list">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">本地端口</label>
            <div class="layui-input-inline">
              <input type="text" id="port" name="port" placeholder="本地监听端口" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">目标地址</label>
            <div class="layui-input-inline">
              <input type="text" id="targetAddr" name="targetAddr" placeholder="转发到地址" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">目标端口</label>
            <div class="layui-input-inline">
              <input type="text" id="targetPort" name="targetPort" placeholder="转发到端口" autocomplete="off" class="layui-input">
            </div>
          </div>

          <div class="layui-inline">
            <button class="layui-btn layuiadmin-btn-list" onclick="query(1);">
              查询
            </button>
          </div>
        </div>
      </div>

      <button class="layui-btn layui-btn-small" onclick="addForward();"><i class="layui-icon"></i> 添加转发</button>      
      <button class="layui-btn layui-btn-small" onclick="delForward();"><i class="layui-icon"></i> 批量删除</button>
      <button class="layui-btn layui-btn-small layui-btn-normal" onclick="AddBatchForward();"><i class="layui-icon"></i> 快速批量添加</button>
      <button class="layui-btn layui-btn-small layui-btn-normal" onclick="ImportForward();"><i class="layui-icon"></i> 批量导入</button>
      
      <div class="layui-form">
        <table class="layui-table">
          <colgroup>
            <col width="20">
            <col width="50">
            <col width="300">
            <col width="150">
            <col width="120">
            <col width="150">
            <col width="50">
            <col width="150">
            <col width="100">
            <col width="70">
            <col width="200">
          </colgroup>
          <thead>
            <tr>
              <th>
                <input type="checkbox" name="" lay-skin="primary" lay-filter="allChoose">
              </th>
              <th>ID</th>
              <th>名称</th>
              <th>本地监听地址</th>
              <th>本地监听端口</th>
              <th>转发方式</th>
              <th>协议</th>
              <th>转发到地址</th>
              <th>转发到端口</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="gridBody">
          </tbody>
        </table>
      </div>
      <div id="pagination"></div>
    </div>
    <div class="layui-tab-item layui-form">
      <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form-item text-right">
                <div class="layui-inline pull-left">
                  <button class="layui-btn layui-btn-small layui-btn-danger" onclick="OpenAllForward();">一键开启</button>
                  <button class="layui-btn layui-btn-small layui-btn-danger" onclick="CloseAllForward();">一键关闭</button>
                </div>
                
            </div>
        </div>
        <pre class="layui-code text-right">
          一键开启说明：
          1、不需要批量勾选规则，只要规则设置了支持“一键开启”都会被一键开启转发。
          2、通过在配置文件中添加  onstart.forward = "true" ，可让程序每次运行后就开始转发该规则。
          3、也可以通过在列表页面通过点击“一键开启” “一键关闭”来开启/关闭所有转发。
        </pre>
        <div class="layui-card-body">
          <div class="layui-form-item text-right">
              <div class="layui-inline pull-left">
                <label class="layui-form-label">详细日志</label>
                <div class="layui-input-block">
                  <input type="checkbox" name="debugStatus" lay-skin="switch" {{if eq .ForWardDebug true}} checked {{end}} lay-filter="ForWardDebug" lay-text="ON|OFF">
                </div>
              </div>
              
          </div>
          
      </div>
      <pre class="layui-code text-right">
        详细日志开关说明：
        1、主要对网络流量突然增大时，连接多、日志多，这个时候不想打印太多日志，可以临时关闭。
        2、详细日志开启时，日志文件会记录较多的后台处理信息，可以帮助分析问题。
        3、开源版本的详细日志，默认开启，只能临时关闭。
      </pre>

    </div>
    </div>
    <div class="layui-tab-item">
      <pre class="layui-code">
说明文档请访问：<a href="https://gitee.com/tavenli/port-forward" target="_blank">https://gitee.com/tavenli/port-forward</a>

使用问题或个性化需求可加QQ号：17020415 （申请时请备注：端口转发）
            </pre>
    </div>
  </div>
</div>
<script id="grid_tpl" type="text/html">
  {Start{# if(d.Data === null || d.Data.length === 0){ }End}
  <tr>
    <td colspan="10">
      查询转发配置规则结果为空
    </td>
  </tr>
  {Start{# } else { }End} {Start{# layui.each(d.Data, function(index, item){ }End}
  <tr>
    <td>
      <input type="checkbox" name="id" lay-skin="primary" value="{Start{ item.Id }End}">
    </td>
    <td>{Start{ item.Id }End}</td>
    <td>{Start{ item.Name }End}</td>
    <td>{Start{ fmtAddr(item.Addr) }End}</td>
    <td>{Start{ item.Port }End}</td>
    <td>{Start{ fmtFType(item.FType) }End}</td>
    <td>{Start{ item.Protocol }End}</td>
    <td>{Start{ item.TargetAddr }End}</td>
    <td>{Start{ item.TargetPort }End}</td>
    <td>{Start{ fmtStatus(item.Status) }End}</td>
    <td>{Start{ oprFormatLink(item.Status,item) }End}</td>
  </tr>
  {Start{# }); }End} {Start{# } }End}
</script>
<script type="text/javascript">
$(document).ready(function() {
  layui.use(["jquery", "layer", "form", "element", "laytpl", "laypage"], function() {
    var $ = layui.jquery,
      layer = layui.layer,
      form = layui.form,
      laytpl = layui.laytpl,
      laypage = layui.laypage;

    var element = layui.element;

    //全选
    form.on('checkbox(allChoose)', function(data) {
      var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
      child.each(function(index, item) {
        item.checked = data.elem.checked;
      });
      form.render('checkbox');
    });

    layui.laytpl.config({
      open: "{Start{",
      close: "}End}"
    });

    element.on('tab(tabForwardList)', function(data){
      console.log(data);
      form.render('checkbox');
      form.render();
    });

    form.on('checkbox()', function(data){
      console.log(data.elem); //得到checkbox原始DOM对象
      console.log(data.elem.checked); //是否被选中，true或者false
      console.log(data.value); //复选框value值，也可以通过data.elem.value得到
      console.log(data.othis); //得到美化后的DOM对象
    }); 

    form.on('switch(ForWardDebug)', function(data){
      $.get("/u/ChangeForwardDebug", {
        rnd: Math.random(),
        status: data.elem.checked?1:0
      }, function(json) {
        
      }, 'json');

    });

    //
    form.render('checkbox');
    form.render();
    //
    query(1);

  });
});

function query(pIndex) {
  // var columnFiled = $("#columnFiled").val();
  // var keyWord = $("#keyWord").val();
  var port = $("#port").val();
  var targetAddr = $("#targetAddr").val();
  var targetPort = $("#targetPort").val();

  $.post("ForwardList/json", {
    port: port,
    targetAddr: targetAddr,
    targetPort: targetPort,
    pIndex: pIndex,
    pSize: 10
  }, function(json) {
    if (json.Code == 0) { //成功
      renderGrid(json.Data);
      var totalPages = json.Data.Pages;
      var totalRows = json.Data.TotalRows;
      //显示分页
      layui.laypage.render({
        elem: 'pagination', //容器
        pages: totalPages, //通过后台拿到的总页数
        count: totalRows,
        limit: 10,
        groups: 5, //连续分页数
        skin: "#51b921", //控制分页皮肤。目前支持：molv、yahei、flow 除此之外，还支持16进制颜色值，如:skin:'#c00'
        curr: pIndex || 1, //当前页
        skip: true,
        layout: ['count','prev', 'page', 'next', 'skip'],
        jump: function(obj, first) { //触发分页后的回调
          if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
            query(obj.curr);
          }
        }
      });
      layui.form.render('checkbox');
    } else { //失败
      layui.layer.alert("失败：" + json.Msg, {
        icon: 2
      });
    }
  }, 'json');
}

function renderGrid(data) {
  var grid_tpl = document.getElementById('grid_tpl').innerHTML;
  layui.laytpl(grid_tpl).render(data, function(html) {
    $("#gridBody").html(html);
  });
}

function oprFormatLink(val, row) {
  var html = "";
  if (row.Status == 1) {
    html += "<button class='layui-btn layui-btn-small layui-btn-danger' onclick='CloseForward(" + row.Id + ");'><i class='layui-icon'></i></button>";
  } else {
    html += "<button class='layui-btn layui-btn-small layui-btn-normal' onclick='OpenForward(" + row.Id + ");'><i class='layui-icon'></i></button>";
  }
  html += "<button class='layui-btn layui-btn-small' onclick='editForward(" + row.Id + ");'><i class='layui-icon'></i></button>";
  return html;
}

function fmtAddr(val) {
  if (val == "") {
    return "监听所有地址";
  } else {
    return val;
  }
}

function fmtFType(val) {
  var html = "";
  switch (val) {
    case 0:
      html = "<font color='blue'>端口到端口映射</font>";
      break;
    case 1:
      html = "<font color='orange'>内网映射 S->C</font>";
      break;
    case 2:
      html = "<font color='red'>内网反向映射 C->S</font>";
      break;
    default:
      html = "<font color='gray'>其它:" + val + "</font>";
      break;
  }
  return html;
}

function fmtStatus(val) {
  var html = "";
  switch (val) {
    case 0:
      html = "<font color='red'>停止</font>";
      break;
    case 1:
      html = "<font color='green'>转发中</font>";
      break;
    default:
      html = "<font color='gray'>其它:" + val + "</font>";
      break;
  }
  return html;
}

function addForward() {
  $.get('/u/AddForward', {
    rnd: Math.random()
  }, function(html) {
    layer.open({
      type: 1, //page层
      area: ['400px', '450px'],
      title: '添加网络转发端口',
      shade: 0.6, //遮罩透明度
      moveType: 1, //拖拽风格，0是默认，1是传统拖动
      shift: -1, //0-6的动画形式，-1不开启
      maxmin: false,
      content: html,
      btn: ['保存配置', '取消'],
      yes: function(index, layero) {
        submitForm(index);
      },
      btn2: function(index) {
        layer.close(index);
      },
      cancel: function(index) {
        layer.close(index);
      }
    });
  });
}

function editForward(id) {
  $.get('/u/EditForward', {
    rnd: Math.random(),
    id: id
  }, function(html) {
    layer.open({
      type: 1, //page层
      area: ['600px', '550px'],
      title: '编辑网络转发端口',
      shade: 0.6, //遮罩透明度
      moveType: 1, //拖拽风格，0是默认，1是传统拖动
      shift: -1, //0-6的动画形式，-1不开启
      maxmin: false,
      content: html,
      btn: ['保存配置', '取消'],
      yes: function(index, layero) {
        submitForm(index);
      },
      btn2: function(index) {
        layer.close(index);
      },
      cancel: function(index) {
        layer.close(index);
      }
    });
  });
}

function delForward() {
  var selectedItems = getChkValues("id");
  if (selectedItems.length == 0) {
    layer.alert("没有勾选要批量操作的数据.", {
      icon: 3,
      title: "警告信息"
    });
    return;
  }
  var ids = selectedItems.join(',');
  layer.confirm("确定批量删除勾选的数据吗？", {
    btn: ['确定', '取消'] //按钮
  }, function(index, layero) {
    $.post("/u/DelForward", {
      rnd: Math.random(),
      ids: ids
    }, function(json) {
      if (json.Code == 0) { //成功
        layer.msg("执行成功.");
        layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
  });
}

function AddBatchForward() {
  $.get('/u/AddBatchForward', {
    rnd: Math.random()
  }, function(html) {
    layer.open({
      type: 1, //page层
      area: ['1200px', '700px'],
      title: '批量添加规则',
      shade: 0.6, //遮罩透明度
      moveType: 1, //拖拽风格，0是默认，1是传统拖动
      shift: -1, //0-6的动画形式，-1不开启
      maxmin: false,
      content: html,
      btn: ['保存', '取消'],
      yes: function(index, layero) {
        submitForm(index);
      },
      cancel: function(index) {
        layer.close(index);
      }
    });
  });
}

function ImportForward() {
  $.get('/u/ImportForward', {
    rnd: Math.random()
  }, function(html) {
    layer.open({
      type: 1, //page层
      area: ['750px', '500px'],
      title: '批量导入规则',
      shade: 0.6, //遮罩透明度
      moveType: 1, //拖拽风格，0是默认，1是传统拖动
      shift: -1, //0-6的动画形式，-1不开启
      maxmin: false,
      content: html,
      btn: ['保存', '取消'],
      yes: function(index, layero) {
        submitForm(index);
      },
      cancel: function(index) {
        layer.close(index);
      }
    });
  });
}

function refreshGrid() {
  query(1);
}

function OpenForward(id) {
  $.post("/u/OpenForward", {
      rnd: Math.random(),
      id: id
    }, function(json) {
      if (json.Code == 0) { //成功
        //layer.msg("执行成功.");
        //layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
}

function CloseForward(id) {
  $.post("/u/CloseForward", {
      rnd: Math.random(),
      id: id
    }, function(json) {
      if (json.Code == 0) { //成功
        //layer.msg("执行成功.");
        //layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
}

function OpenForward2(id) {
  layer.confirm("确定启动该转发吗？", {
    btn: ['确定', '取消'] //按钮
  }, function(index, layero) {
    $.post("/u/OpenForward", {
      rnd: Math.random(),
      id: id
    }, function(json) {
      if (json.Code == 0) { //成功
        layer.msg("执行成功.");
        layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
  });
}

function CloseForward2(id) {
  layer.confirm("确定停止该转发吗？", {
    btn: ['确定', '取消'] //按钮
  }, function(index, layero) {
    $.post("/u/CloseForward", {
      rnd: Math.random(),
      id: id
    }, function(json) {
      if (json.Code == 0) { //成功
        layer.msg("执行成功.");
        layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
  });
}

function OpenAllForward() {
  layer.confirm("确定一键开启所有转发吗？", {
    btn: ['确定', '取消'] //按钮
  }, function(index, layero) {
    $.post("/u/OpenAllForward", {
      rnd: Math.random()
    }, function(json) {
      if (json.Code == 0) { //成功
        layer.msg("执行成功.");
        layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
  });
}

function CloseAllForward() {
  layer.confirm("确定一键关闭所有转发吗？", {
    btn: ['确定', '取消'] //按钮
  }, function(index, layero) {
    $.post("/u/CloseAllForward", {
      rnd: Math.random()
    }, function(json) {
      if (json.Code == 0) { //成功
        layer.msg("执行成功.");
        layer.close(index);
        query(1);
      } else { //失败
        layer.alert(json.Msg, {
          icon: 2
        });
        query(1);
      }
    }, 'json');
  });
}
</script>
